<?php
namespace yan\editor_frontend\editorxml;
use Yii;
use yii\helpers\Html;
class EditorWidget extends \yii\base\Widget{
	public $id;
	public $type;
	public $lang;
	public $data;
	public $widgets;

	private $_widgets = [
		'layout' => WebLayoutWidget::class,
		'editor' => WebEditorWidget::class,
		'images' => WebImagesWidget::class,
		'image' => WebImageWidget::class,
		'text' => WebTextWidget::class,
		'textH1' => WebTextH1Widget::class,
		'slider' => WebSliderWidget::class,
		'homeSlider' => WebHomeSliderWidget::class,
		'collapse' => WebCollapseWidget::class,
		'listContainer' => WebListContainerWidget::class,
		'container' => WebContainerWidget::class,
		'tabs' => WebTabsWidget::class,
	];
	public function init(){
		if(!empty($this->widgets)){
			foreach ($this->widgets as $key => $value) {
				$this->_widgets[$key] = $value;
			}
		}
	}
	public function run(){
		
		$shtml = '';
		if(!empty($this->data)){
			foreach ($this->data as $key => $val) {
				$inner = $this->renderNode($key, $val);
				$shtml .= Html::tag('section', $inner);
			}
		}

		return $shtml;
	}
	public static function isDigit($string){
        $pattern = '/^[0-9]*$/u';
        $flag = preg_match($pattern, $string, $matches);
        if ($flag) {
            return true;
        } else {
            return false;
        }
    }
	public function renderNode($type, $val, $parent_type = '', $levevl=0){
		if($levevl >10) return null;
		$nodeNames = explode('_', $type);
		$type = $nodeNames['0'];
		$attributes = isset($val['@attributes']) ? $val['@attributes'] : null;

		if(!empty($attributes)){
			$widget_id = isset($attributes['id']) ? $attributes['id'] : null;
			$widget_data = isset($attributes['data']) ? json_decode($attributes['data'], true) :[];
			$ids  = explode('_', $widget_id);
			if($ids[0]!=$type){
				$type = $ids[0];	
			}
		}
		if(isset($val['@attributes']))
			unset($val['@attributes']);
		$child = [];
		if(!empty($val) && is_array($val)){
			foreach($val as $node_type => $child_node){
				$child[] = $this->renderNode($node_type, $child_node, $type, ($levevl+1));
			}
		}
		return $this->renderWidget($type, isset($widget_data) ? $widget_data : null, $parent_type, $child);
	}
	public function renderWidget($type, $val, $parent_node='', $child_html=[]){
		if(isset($this->_widgets[$type])){
			$widgetClass = $this->_widgets[$type];
			$shtml = $widgetClass::widget([
				'value'=> $val, 
				'child'=> $child_html,
				'that' => $this,
				'parent_type' => $parent_node,
			]);
			return $shtml;
		}	
		return null;
	}
}